#ifndef TCP_SERVE_HPP
#define TCP_SERVE_HPP

#include <iostream>
#include <cstdio>
#include <string>
#include <unordered_map>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <signal.h>
#include <unistd.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <ctype.h>
#include "log.hpp"

class TcpServer
{
private:
    const static int gbacklog = 20;

public:
    TcpServer(uint16_t port, std::string ip = "0.0.0.0")
        : _port(port), _ip(ip), _listensock(-1)
    {
    }

    void InitServer()
    {
        // 1.创建套接字
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            logMessage(FATAL, "socket creat error! %d : %s", errno, strerror(errno));
            exit(-1);
        }
        logMessage(NORMAL, "socket creat successfully! %d", _listensock);

        // 2.绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &local.sin_addr);
        // 函数原型：int inet_pton(int family, const char *strptr, void *addrptr);
        // inet_aton(_ip.c_str(), &local.sin_addr);
        // local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());
        if (bind(_listensock, (struct sockaddr *)&local, sizeof local) < 0)
        {
            logMessage(FATAL, "bind error! %d : %s", errno, strerror(errno));
            exit(-2);
        }

        // 3.因为tcp是面向连接的，所以我们需要先建立连接，即将套接字设置为监听状态
        if (listen(_listensock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error! %d : %s", errno, strerror(errno));
            exit(-3);
        }

        logMessage(NORMAL, "init server success");
    }


    void Start()
    {
        while(true)
        {
            struct sockaddr_in seversock;
            socklen_t len = sizeof seversock;
            int sock = accept(_listensock, (struct sockaddr*)&seversock, &len);
            if(sock < 0)
            {
                logMessage(FATAL, "connect error! %d : %s", errno, strerror(errno));
                exit(-4);
            }

            //链接成功
            //v1:单进程循环版本
            while(true)
            {
                char buffer[1024];
                ssize_t s = recv(sock, buffer, sizeof buffer, 0);
                if(s > 0)
                {
                    buffer[s] = 0;
                }
                send(sock, buffer, sizeof buffer, 0);
            }
            close(sock);
        }
    }

    ~TcpServer(){}


private:
    uint16_t _port;
    std::string _ip;
    int _listensock;
};

#endif